﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Business;
using Business.Common;

/// <!--
/// 功能描述  : 持久化控件
/// 创建人  : Wu Hansi
/// 创建时间: 2007-07-09
/// -->
public partial class UserControls_PersistenceControl : System.Web.UI.UserControl
{
    private string[] readControlAcrnyms = { "txt", "ddl", "ckb", "rdb", "lbl", "hfd" };

    private bool isMaster = true;
    private string contentPlaceHolder = "ContentPlaceHolderContent";
    private Control pageControl;

    private Hashtable mapTable;

    #region 属性
    /// <summary>
    /// 关联的表名
    /// </summary>
    public string Table
    {
        get
        {
            return ViewState["Table"] as string;
        }
        set
        {
            ViewState["Table"] = value;
        }
    }

    /// <summary>
    /// 生成的新关键值
    /// </summary>
    public string NewKeyValue
    {
        get
        {
            return ViewState["NewKeyValue"] as string;
        }
        set
        {
            ViewState["NewKeyValue"] = value;
        }
    }

    /// <summary>
    /// 检索的关键字
    /// </summary>
    public string Key
    {
        get
        {
            return ViewState["Key"] as string;
        }
        set
        {
            ViewState["Key"] = value;
        }
    }

    /// <summary>
    /// 关键字值
    /// </summary>
    public String KeyValue
    {
        get
        {
            return ViewState["KeyValue"] as string;
        }
        set
        {
            ViewState["KeyValue"] = value;
        }
    }

    /// <summary>
    /// 待查找的所有子控件的父容器
    /// </summary>
    public Control PageControl
    {
        get
        {
            if (pageControl != null)
            {
                return pageControl;
            }
            else if (isMaster)
            {
                return Page.Master.FindControl(contentPlaceHolder);
            }
            else
            {
                return Page;
            }
        }
        set
        {
            pageControl = value;
        }
    }

    /// <summary>
    /// 页面状态
    /// </summary>
    public string Status
    {
        get
        {
            return hfStatus.Value;
        }
        set
        {
            hfStatus.Value = value;
        }
    }

    /// <summary>
    /// 是否使用Button
    /// </summary>
    public bool EnableButton
    {
        get
        {
            if (ViewState["PersistenceControl_EnableButton"] == null)
            {
                return false;
            }
            else
            {
                return (bool)ViewState["PersistenceControl_EnableButton"];
            }
        }
        set { ViewState["PersistenceControl_EnableButton"] = value; }
    }

    /// <summary>
    /// 返回的地址
    /// </summary>
    public string ReturnUrl
    {
        get { return ViewState["PsersistenceControl_ReturnUrl"] as string; }
        set { ViewState["PsersistenceControl_ReturnUrl"] = value; }
    }

    /// <summary>
    /// 如果子项为时间控件，是否显示短日期格式
    /// </summary>
    public bool AppearCalendarTime
    {
        get {
            if (ViewState["PsersistenceControl_AppearCalendarTime"] == null)
            {
                return false;
            }
            else
            {
                return (bool)ViewState["PsersistenceControl_AppearCalendarTime"];
            }
        }
        set { ViewState["PsersistenceControl_AppearCalendarTime"] = value; }
    }

    /// <summary>
    /// 其他查询条件
    /// </summary>
    /// cd 修改于 2007-07-30    
    ///修改事由：增加该属性以使控件能够接收其他查询条件
    public string OtherCondition
    {
        get
        {
            return ViewState["OtherCondition"] == null ? string.Empty : ViewState["OtherCondition"].ToString();
        }
        set
        {
            ViewState["OtherCondition"] = value;
        }
    }
    #endregion

    #region 页面加载
    /// <summary>
    /// 页面加载
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(Status))
        {
            if (Request.Params["action"] == "query")
            {
                Status = "view";
            }
        }
        
        Status = Status.ToLower();

        if (EnableButton)
        {
            if (Status == "view" || Status == "query")
            {
                btnSave.Visible = false;
            }
            else
            {
                btnSave.Visible = true;
            }
        }
        else
        {
            btnSave.Visible = false;
        }

        btnReturn.Visible = EnableButton;
    }
    #endregion

    #region 展现控件
    /// <summary>
    /// 展现控件
    /// </summary>
    public void Render()
    {
        DataTable dtTable = CommonOperationQuery.GetCqEvaluateDetail(Table, Key, KeyValue,"");
        if (!string.IsNullOrEmpty(OtherCondition))
        {
            dtTable = CommonOperationQuery.GetCqEvaluateDetail(Table, Key, KeyValue, OtherCondition);
        }

        if (dtTable.Rows.Count > 0)
        {
            Read();
            if (Status == "view" || Status == "query")
            {
                LockControl();
            }
        }
        else
        {
            //设置状态为insert
            Status = "insert";
        }

        //一个比较偷懒的写法，直接操作评估管理的一些页面了
        if (Status == "view" || Status == "query")
        {
            if (pageControl != null)
            {
                Control button = pageControl.FindControl("btn_Insert");
                if (button != null)
                {
                    button.Visible = false;
                }
                else
                {
                    button = pageControl.FindControl("btnCommit");
                }
                
            }
        }

    }
    #endregion

    #region 从数据库中读数据，写到控件中
    /// <summary>
    /// 从数据库中读数据，写到控件中
    /// </summary>
    /// <param name="id"></param>
    public void Read()
    {
        DoMapping(true);
        DataTable dtTable = CommonOperationQuery.GetCqEvaluateDetail(Table, Key, KeyValue,"");
        if (!string.IsNullOrEmpty(OtherCondition))
        {
            dtTable = CommonOperationQuery.GetCqEvaluateDetail(Table, Key, KeyValue, OtherCondition);
        }
        if (dtTable.Rows.Count == 0)
        {
            return;
        }
        DataRow rowData = dtTable.Rows[0];
        foreach (string key in mapTable.Keys)
        {
            try
            {
                if (rowData[key] != null)
                {
                    Control control = PageControl.FindControl(mapTable[key].ToString());
                    if (control == null)
                        control = (Control)GetChildControl(mapTable[key].ToString());
                    PopulateControl(control, rowData[key].ToString());
                }
            }
            catch
            {
            }
        }
        //LockControl();
        //if (Status == "edit")
        //{
        //    UnlockControl();
        //}
    }
    #endregion

    #region Update
    /// <summary>
    /// 把页面中的数据更新到数据库中, SaveOrUpdate
    /// </summary>
    public void Update()
    {
        Update(false);

    }
    /// <summary>
    /// 更新
    /// </summary>
    /// <param name="?"></param>
    public void Update(bool needSync)
    {
        if (string.IsNullOrEmpty(KeyValue) || CommonOperationQuery.GetCqEvaluateDetail(Table, Key, KeyValue,"").Rows.Count == 0)
        {
            //设置状态为view
            Status = "view";
            Insert();
        }
        else
        {
            DoMapping(false);
            if (!CommonOperationQuery.UpdateCqEvaluate(Table, Key, KeyValue, PopulateHashTable()))
            {
                throw new Exception("更新失败");
            }
        }
    }
    #endregion

    #region 对外开放的一些操作,Insert(), Delete, Update, Query()
    /// <summary>
    /// 插入
    /// </summary>
    public void Insert()
    {
        DoMapping(true);

        object objNewKey=null;
        if (!CommonOperationQuery.InsertCqEvaluate(Table, Key, KeyValue, PopulateHashTable(), ref objNewKey))
        {
            throw new Exception("插入失败");
        }

        if (objNewKey != null)
        {
            NewKeyValue = objNewKey.ToString();
        }
    }

    /// <summary>
    /// 删除
    /// </summary>
    public void Delete()
    {
        if (!CommonOperationQuery.DeleteCqEvaluate(Table, Key, KeyValue))
        {
            throw new Exception("删除失败");
        }
    }

    /// <summary>
    /// 得到查询条件
    /// </summary>
    /// <returns></returns>
    public Hashtable GetQueryConditions()
    {
        DoMapping(true);
        return PopulateHashTable();
    }
    #endregion

    #region 生成控件和字段的映射
    /// <summary>
    /// 生成控件和字段的映射
    /// </summary>
    /// <param name="bGetLabelText">获取label控件的值</param>
    private void DoMapping(bool bGetLabelText)
    {
        //如果已经做好了映射就退出
        if (mapTable != null)
        {
            return;
        }
        mapTable = new Hashtable(32);
        foreach (Control control in PageControl.Controls)
        {
            //add TabControl processing
            if (control is WebControls.TabControl)
            {
                foreach (Control innercontrol in control.Controls)
                {
                    if (innercontrol is WebControls.TabPage)
                    {
                        foreach (Control pagecontrol in innercontrol.Controls)
                        {
                            foreach (string acronym in readControlAcrnyms)
                            {
                                if (pagecontrol.ID != null && pagecontrol.ID.StartsWith(acronym))
                                {
                                    string fieldName = pagecontrol.ID.Substring(acronym.Length);
                                    mapTable[fieldName] = pagecontrol.ID;
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                foreach (string acronym in readControlAcrnyms)
                {
                    //根据标志位确定是否获取label的值
                    if( (acronym.CompareTo("lbl") == 0) && !bGetLabelText)
                    {
                        continue;
                    }

                    if (control.ID != null && control.ID.StartsWith(acronym))
                    {
                        string fieldName = control.ID.Substring(acronym.Length);
                        mapTable[fieldName] = control.ID;
                    }
                }
            }

        }
    }
    #endregion

    #region 填充页面控件
    /// <summary>
    /// 填充页面控件
    /// </summary>
    /// <param name="control"></param>
    /// <param name="value"></param>
    private void PopulateControl(Control control, string value)
    {
        ControlCollection cc = control.Parent.Controls;
        if (control is TextBox)
        {
            TextBox txt = (TextBox)control;
            txt.Text = value;
        }
        if (control is Label)
        {
            Label lbl = (Label)control;
            lbl.Text = value;
        }
        else if (control is RadioButtonList)//add by lj
        {
            RadioButtonList rbl = (RadioButtonList)control;
            rbl.SelectedValue = value;
        }
        else if (control is DropDownList)
        {
            DropDownList ddl = (DropDownList)control;
            ddl.SelectedValue = value;
        }
        else if (control is HiddenField)//add by lj
        {
            HiddenField hfdCtl = (HiddenField)control;
            hfdCtl.Value = value;
        }
        else if (control is CheckBox)
        {
            CheckBox ckb = (CheckBox)control;
            if (value == "1")
            {
                ckb.Checked = true;
            }
            else
            {
                ckb.Checked = false;
            }
        }
        else if (control is UserControl)
        {
            if (control is Controls_Com_Calendar)
            {
                Controls_Com_Calendar calendar = (Controls_Com_Calendar)control;
                if (value != string.Empty)
                {
                    if (!AppearCalendarTime)
                    {
                        DateTime date = Convert.ToDateTime(value);
                        calendar.Text = date.ToShortDateString();
                    }
                    else
                    {
                        calendar.Text = value;
                    }
                }
            }
            else if (control is UserControls_GeneralSelect)
            {
                UserControls_GeneralSelect general = (UserControls_GeneralSelect)control;
                general.SelectedValue = value;
            }
            else if (control is WebControls.IUserControl)
            {
                WebControls.IUserControl userControl = (WebControls.IUserControl)control;
                userControl.Value = value;
            }            
        }
    }

    #endregion

    #region 查找自定义控件中的包含子控件
    /// <summary>
    /// 查找自定义控件中的包含子控件
    /// </summary>
    /// <param name="strNeedFindControlName"></param>
    /// <returns></returns>
    private object GetChildControlText(string strNeedFindControlName)
    {
        string strControlValue = string.Empty;
        foreach (Control control in PageControl.Controls)
        {
            //判断是否为ANTU控件,查找子控件
            if (control is WebControls.TabControl)
            {
                WebControls.TabControl tabCtrl = control as WebControls.TabControl;

                foreach (Control ctrlChild in tabCtrl.Controls)
                {
                    //查找TABPAGE子控件
                    if (ctrlChild is WebControls.TabPage)
                    {
                        Control ctrlFinally=null;
                        if (ctrlChild.FindControl(strNeedFindControlName) != null)
                        {
                            ctrlFinally = ctrlChild.FindControl(strNeedFindControlName);
                        }
                        if (ctrlFinally != null)
                        {
                            strControlValue = GetControlValue(ctrlFinally);
                        }
                    }
                }
            }
            if (control is WebControls.TabPage)
            {
                //查找TABPAGE子控件
                Control ctrlFinally = null;
                if (control.FindControl(strNeedFindControlName) != null)
                {
                    ctrlFinally = control.FindControl(strNeedFindControlName);
                }

                if (ctrlFinally != null)
                {
                    strControlValue = GetControlValue(ctrlFinally);
                }
            }
        }

        return strControlValue;
    } 
    #endregion

    #region 获取自定义控件中的包含子控件
    /// <summary>
    /// 获取自定义控件中的包含子控件
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    private object GetChildControl(string name)
    {
        Control retControl=null;
        foreach (Control control in PageControl.Controls)
        {
            if (control is WebControls.TabControl)
            {
                foreach (Control childcontrol in control.Controls)
                {
                    if (childcontrol is WebControls.TabPage)
                    {
                        if (childcontrol.FindControl(name) != null)
                        {
                            retControl = childcontrol.FindControl(name);
                        }
                    }
                }
            }   
        }
        return retControl;
    }
    #endregion

    #region 查找指定控件下的所有子控件
    /// <summary>
    /// 查找指定控件下的所有子控件
    /// </summary>
    /// <param name="ctrlParam"></param>
    /// <returns></returns>
    private string GetControlValue(Control control)
    {
        string strReturn = string.Empty;
        if (control is TextBox)
        {
            TextBox txt = (TextBox)control;
            strReturn = txt.Text;
        }
        else if (control is Label)
        {
            //continue;
        }
        else if (control is RadioButtonList)//add by lj
        {
            RadioButtonList rbl = (RadioButtonList)control;
            strReturn = rbl.SelectedValue;
        }
        else if (control is DropDownList)
        {
            DropDownList ddl = (DropDownList)control;
            strReturn = ddl.SelectedValue;
        }
        else if (control is CheckBox)
        {
            CheckBox ckb = (CheckBox)control;
            if (ckb.Checked)
            {
                strReturn = "1";
            }
            else
            {
                strReturn = "0";
            }
        }
        else if (control is HiddenField)
        {
            HiddenField hfd = (HiddenField)control;
            if (hfd.Value != string.Empty)
            {
                strReturn = hfd.Value;
            }
        }
        else if (control is UserControl)
        {
            if (control.GetType().Name.CompareTo("Controls_Com_Calendar")==0)
            {
                Controls_Com_Calendar calendar = (Controls_Com_Calendar)control;
                if (calendar.Text != string.Empty)
                {
                    strReturn = "to_date('" + calendar.Text + "','yyyy-mm-dd hh24:mi:ss')";
                }
            }
            else if (control is UserControls_GeneralSelect)
            {
                UserControls_GeneralSelect general = (UserControls_GeneralSelect)control;
                strReturn = general.SelectedValue;
            }
            else if (control is WebControls.IUserControl)
            {
                WebControls.IUserControl userControl = (WebControls.IUserControl)control;
                strReturn = userControl.Value;
            }
        }
        return strReturn;
    } 
    #endregion

    #region 读取页面输入
    /// <summary>
    /// 读取页面输入
    /// </summary>
    /// <returns></returns>
    private Hashtable PopulateHashTable()
    {
        Hashtable datas = new Hashtable(32);
        foreach (string key in mapTable.Keys)
        {
            Control control = PageControl.FindControl(mapTable[key].ToString());

            if (control != null)
            {
                datas[key] = GetControlValue(control);
            }            
            else if (control == null)
            {
                datas[key] = GetChildControlText(mapTable[key].ToString());
            }
        }
        return datas;
    }
    #endregion

    #region 点击操作响应，有状态更新
    protected void btnSave_Click(object sender, EventArgs e)
    {
        ExecuteWithStatus();
    }

    protected void btnReturn_Click(object sender, EventArgs e)
    {
        if (Status == "query")
        {
            Response.Write("<script type='text/javascript'>history.go(-2)</script>");
        }
        else
        {
            Response.Redirect(ReturnUrl);
        }
    }

    public void ExecuteWithStatus()
    {
        if (Status == "view")
        {
            UnlockControl();
            Status = "edit";
        }
        else if (Status == "edit" || Status == "insert")
        {
            Update();
            LockControl();
            Status = "view";
        }
    }
    #endregion

    #region 锁定、解锁控件
    /// <summary>
    /// 使页面控件都只读
    /// </summary>
    public void UnlockControl()
    {
        if (Status == "query")
        {
            return;
        }
        DoMapping(true);
        ControlCollection cc = PageControl.Controls;
        foreach (Control control in cc)
        {
            if (control is TextBox)
            {
                TextBox txt = (TextBox)control;
                txt.ReadOnly = false;
                txt.Enabled = true;
            }
            else if (control is DropDownList)
            {
                DropDownList ddl = (DropDownList)control;
                ddl.Enabled = true;
            }
            else if (control is CheckBox)
            {
                CheckBox ckb = (CheckBox)control;
                ckb.Enabled = true;
                ckb.Attributes.Remove("onclick");
                ckb.InputAttributes.Remove("onmousemove");
            }
            else if (control is WebControls.TabControl)
            {
                foreach (Control childcontrol in control.Controls)
                {
                    if (childcontrol is WebControls.TabPage)
                    {
                        foreach (Control cchildcontrol in childcontrol.Controls)
                        {
                            if (cchildcontrol is TextBox)
                            {
                                TextBox txt = (TextBox)cchildcontrol;
                                txt.ReadOnly = false;
                                txt.Enabled = true;
                            }
                            else if (cchildcontrol is DropDownList)
                            {
                                DropDownList ddl = (DropDownList)cchildcontrol;
                                ddl.Enabled = true;
                            }
                            else if (cchildcontrol is CheckBox)
                            {
                                CheckBox ckb = (CheckBox)cchildcontrol;
                                ckb.Enabled = true;
                                ckb.Attributes.Remove("onclick");
                                ckb.Attributes.Remove("onmousemove");
                            }
                            else if (cchildcontrol is UserControl)
                            {
                                if (cchildcontrol is Controls_Com_Calendar)
                                {
                                    Controls_Com_Calendar calendar = (Controls_Com_Calendar)cchildcontrol;
                                    calendar.ReadOnly = false;
                                    calendar.ShowCalendar = true;
                                }
                                else if (cchildcontrol is UserControls_GeneralSelect)
                                {
                                    UserControls_GeneralSelect general = (UserControls_GeneralSelect)cchildcontrol;
                                    general.ReadOnly = false;
                                }
                                else if (cchildcontrol is WebControls.IUserControl)
                                {
                                    WebControls.IUserControl userControl = (WebControls.IUserControl)cchildcontrol;
                                    userControl.ReadOnly = false;
                                }
                            }
                        }
                    }
                }
            }
            else if (control is UserControl)
            {
                if (control is Controls_Com_Calendar)
                {
                    Controls_Com_Calendar calendar = (Controls_Com_Calendar)control;
                    calendar.ReadOnly = false;
                    calendar.ShowCalendar = true;
                }
                else if (control is UserControls_GeneralSelect)
                {
                    UserControls_GeneralSelect general = (UserControls_GeneralSelect)control;
                    general.ReadOnly = false;
                }
                else if (control is WebControls.IUserControl)
                {
                    WebControls.IUserControl userControl = (WebControls.IUserControl)control;
                    userControl.ReadOnly = false;
                }                

            }            
        }
        btnSave.Text = "保存";
    }

    /// <!--
    /// 创建人  : Wu Hansi
    /// 创建时间: 2007-07-09
    /// 修改人  : Wu Hansi
    /// 修改时间: 2007-07-09
    /// 修改描述: 描述
    /// -->
    public void LockControl()
    {
        DoMapping(true);
        foreach (string key in mapTable.Keys)
        {
            try
            {
                if (mapTable[key] != null)
                {
                    Control control = PageControl.FindControl(mapTable[key].ToString());
                    if(control==null)
                        control =(Control)GetChildControl(mapTable[key].ToString());
                    DoLockControl(control);
                }
            }
            catch (ArgumentException ae)
            {
                throw ae;
            }
        }

    }

    /// <summary>
    /// 锁定控件
    /// </summary>
    /// <param name="control"></param>
    private void DoLockControl(Control control)
    {
        ControlCollection cc = PageControl.Controls;
        if (control is TextBox)
        {
            TextBox txt = (TextBox)control;
            txt.ReadOnly = true;
        }
        else if (control is DropDownList)
        {
            DropDownList ddl = (DropDownList)control;
            ddl.Enabled = false;
        }
        else if (control is CheckBox)
        {
            CheckBox ckb = (CheckBox)control;
            ckb.Attributes.Remove("onclick");
            if (control is RadioButton)
            {
                
                //RadioButton不可用  by cd 2008-6-14
                //鼠标移动时记录选定值
                ckb.InputAttributes.Add("onmousemove", @"javascript:var rdbList=document.getElementsByName(this.name);
                if(rdbList!=null)
                {
                    for(i=0;i<rdbList.length;i++)
                    {
                        if(rdbList[i].checked)
                        {
                            this.title=rdbList[i].id;
                            break;
                        }
                    }
                }");
                //点击时恢复为记录的状态
                ckb.Attributes.Add("onclick", @"javascript:this.checked=false;if(this.title!='')
                {var rdb=document.getElementById(this.title);if(rdb!=null){rdb.checked=true;}}");
            }
            else
            {
                ckb.Attributes.Add("onclick", "javascript:this.checked=!this.checked;");//CheckBox不可用  by cd 2007-9-28
            }
        }
        else if (control is UserControl)
        {
            if (control is Controls_Com_Calendar)
            {
                Controls_Com_Calendar calendar = (Controls_Com_Calendar)control;
                calendar.ReadOnly = true;
                calendar.ShowCalendar = false;
            }
            else if (control is UserControls_GeneralSelect)
            {
                UserControls_GeneralSelect general = (UserControls_GeneralSelect)control;
                general.ReadOnly = true;
            }
            else if (control is WebControls.IUserControl)
            {
                WebControls.IUserControl userControl = (WebControls.IUserControl)control;
                userControl.ReadOnly = true;
            }
        }
        btnSave.Text = "修改";
    }
    #endregion
}
